<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\UsersService;
use app\admin\service\UsersMemberService;
use app\admin\service\UsersAccessLogService;
use app\admin\service\IdentityService;
use app\AdminController;

/**
 * 用户
 * Class Users
 * @package app\admin\controller
 */
class Users extends AdminController
{
    /**
     * 用户列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (request()->isPost()) {
            $where[] = ['u.associate', 'not in', [-1, -2]];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['u.nickname|u.auth_city', 'like', '%' . $keywords . '%'];
            }

            // 身份搜索
            $identity_id = $this->request->param('identity_id', '-1');
            if ($identity_id != '-1') {
                $where[] = ['c.identity_id', '=', $identity_id];
            }

            // 角色搜索
            $role = $this->request->param('role', '-1');
            if ($role != '-1') {
                $where[] = ['u.role', '=', $role];
            }

            // 来源搜索
            $associate = $this->request->param('associate', '-1');
            if ($associate != '-1') {
                $where[] = ['u.associate', '=', $associate];
            }

            // 状态搜索
            $state = $this->request->param('state', '-1');
            if ($state != '-1') {
                $where[] = ['u.state', '=', $state];
            }

            $list = UsersService::getUsersList($where, $this->page, $this->pagesize);
            $count = UsersService::countUsersList($where);
            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        // 用户总数
        $countUsers = UsersService::countUsers();
        // 今日新增
        $todayUsers = UsersService::todayUsers();
        // VIP总数
        $countUsersMember = UsersMemberService::countUsersMember();
        // 游客总数
        $countTourist = $countUsers - $countUsersMember;
        // 周访问
        $usersAccessWeekLine = UsersAccessLogService::getUsersAccessWeekLine();
        // 本周访问量
        $countUsersAccessWeek = UsersAccessLogService::countUsersAccessWeek();
        // 当月访问量
        $countUsersAccessMonth = UsersAccessLogService::countUsersAccessMonth();
        // 当日访问量
        $countUsersAccessToday = UsersAccessLogService::todayAccess();
        // 今年访问量
        $countUsersAccessYear = UsersAccessLogService::countUsersAccessYear();
        // 身份数据
        $identityList = IdentityService::getIdentityList();

        return view('', [
            'countUsers' => $countUsers,
            'countUsersMember' => $countUsersMember,
            'todayUsers' => $todayUsers,
            'countTourist' => $countTourist,
            // 访问数据
            'usersAccessWeekLine' => $usersAccessWeekLine,
            'countUsersAccessWeek' => $countUsersAccessWeek,
            'countUsersAccessMonth' => $countUsersAccessMonth,
            'countUsersAccessToday' => $countUsersAccessToday,
            'countUsersAccessYear' => $countUsersAccessYear,
            'identityList' => $identityList,
        ]);
    }

    /**
     * 会员升级
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function upGradeMember()
    {
        $id = intval($this->request->param('id', 0));
        $day = intval($this->request->param('day', 0));
        if (!$id || !$day) {
            $this->error(adminJsonMsg(1001));
        }
        $where = ['id' => $id];
        $users = UsersService::findUsers($where);
        if (!$users) {
            $this->error(adminJsonMsg(1002));
        }

        $memberWhere = ['uid' => $users['id']];
        $usersMember = UsersMemberService::findUsersMember($memberWhere);
        $time = $day * 3600 * 24;
        if ($usersMember) {
            //表示更新
            if ($usersMember['end_time'] > time()) {
                $endTime = $usersMember['end_time'] + $time;
            } else {
                $endTime = $time + time();
            }
            // 更新到期时间后，到期通知的状态字段更改为默认状态
            // 累加购买次数
            $res = UsersMemberService::updateUsersMember(['end_time' => $endTime, 'is_push' => 0, 'buy_nums' => $usersMember['buy_nums'] + 1], $memberWhere);
        } else {
            $arr = [];
            $arr['uid'] = $users['id'];
            $arr['code'] = generateCode();
            $arr['start_time'] = time();
            $arr['end_time'] = $time + time();
            $arr['type'] = 1;
            $res = UsersMemberService::createUsersMember($arr);

            // 更新用户角色
            UsersService::updateUsers(['role' => 2], ['id' => $users['id']]);
        }

        if (!$res) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $where = ['id' => $id];
        $users = UsersService::findUsers($where);
        if (!$users) {
            $this->error(adminJsonMsg(1002));
        }

        $state = $users['state'] == 1 ? 0 : 1;
        $result = UsersService::updateUsers(['state' => $state], $where);
        if (!$result) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }
}